import time
from PV_Factory import PV_Factory as pf
from os.path import isfile
from config import get_config

if isfile("./config.py"):
    from config import get_config

pv_datas = get_config()["PV"]


def power_set(now_power: float, set_power: float, _time: int):
    step = (set_power - now_power) / (_time * 10)
    print("步长为：", step)
    power = now_power

    while True:
        if pf.create_pv(pv_datas["急停开关"]).get() == 1:
            break
        power += step
        if (now_power <= set_power and power >= set_power) or (
            now_power >= set_power and power <= set_power
        ):
            power = set_power
            # print("设定功率为：", power)
            pf.create_pv(pv_datas["幅度驱动"]).put(power)
            break
        # print("设定功率为：", power)
        pf.create_pv(pv_datas["幅度驱动"]).put(power)
        time.sleep(0.1)
    # time.sleep(0.1)


def keep_time(wait_time: float, flag=False):
    start_time = time.time()
    while time.time() - start_time <= wait_time:
        time.sleep(0.1)
        if pf.create_pv(pv_datas["急停开关"]).get() == 1:
            break
    if flag:
        pf.create_pv(pv_datas["当前清洗时间"]).put(
            pf.create_pv(pv_datas["当前清洗时间"]).get()
            + round(float(time.time() - start_time), 1)
        )
